package com.z.sys.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.z.common.configure.proprety.TemplateProperty;
import com.z.common.context.UserContext;
import com.z.common.utils.SequenceUtil;
import com.z.sys.entity.SysFile;
import com.z.sys.mapper.SysFileMapper;
import com.z.common.utils.ImageBase64Util;
import com.z.common.utils.upload.FileUtil;
import com.z.common.web.vo.request.PageVo;
import com.z.sys.entity.Dept;
import com.z.sys.entity.User;
import com.z.sys.mapper.UserMapper;
import com.z.sys.service.IDeptService;
import com.z.sys.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.time.LocalDate;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 员工管理Service业务层处理
 *
 * @author z
 * @date 2022-11-07
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper,User> implements IUserService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private IDeptService deptService;
    /**
     * 引 入 服 务
     */
    @Resource
    private SysFileMapper fileMapper;

    /**
     * 上 传 可 读 配 置
     */
    @Resource
    private TemplateProperty uploadProperty;
    /**
     * 查询员工管理
     * @param user 员工管理
     * @param pageVo
     * @param m
     * @return 员工管理 分页集合
     * */
    @Override
    public PageInfo<User> selectUserPage(User user, PageVo pageVo, String m) {
        PageHelper.startPage(pageVo.getPage(), pageVo.getLimit());
        List<User> data = selectUserList(user, m);
        return new PageInfo<>(data);
    }
    @Override
    public List<User> selectUserList(User user, String m) {
        if(StringUtils.isEmpty(m)){
            m = "人事";
        }
        int powerLevel = UserContext.getPowerLevel(m);
        if(powerLevel == 0){
            user.setDeptId(null);
            user.setDeptName("");
        } else if(powerLevel == 1){
            String full_path_sql = "";
            List<Dept> deptList = deptService.getUnitListByRole(m);
            if(deptList != null && deptList.size() > 0){
                full_path_sql = "(";
                for(Dept dept : deptList){
                    full_path_sql += ("d.full_path like '" + dept.getFullPath() + "/%' or d.full_path = '" + dept.getFullPath() + "' or ");
                };
                full_path_sql = full_path_sql.substring(0, full_path_sql.length()-3) + ")";
            }
            Map<String, Object> map = new HashMap<>();
            map.put("full_path_sql", full_path_sql);
            user.setParams(map);
        } else {
            String full_path_sql = "";
            List<Dept> deptList = deptService.getDeptListByRole();
            if(deptList != null && deptList.size() > 0){
                full_path_sql = "(";
                for(Dept dept : deptList){
                    full_path_sql += ("d.full_path like '" + dept.getFullPath() + "/%' or d.full_path = '" + dept.getFullPath() + "' or ");
                };
                full_path_sql = full_path_sql.substring(0, full_path_sql.length()-3) + ")";
            }
            Map<String, Object> map = new HashMap<>();
            map.put("full_path_sql", full_path_sql);
            user.setParams(map);
        }
        return baseMapper.selectUserList(user);
    }

    @Override
    public boolean save(User entity) {
        if(StringUtils.isEmpty(entity.getPassword())){
            entity.setPassword(new BCryptPasswordEncoder().encode("1111") );
        }
        return super.save(entity);
    }

    @Override
    public boolean updateEnableById(User user) {
        return userMapper.updateEnableById(user);
    }

    /**
     * Describe: 文件上传
     * Param: File
     * Return: id
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String upload(MultipartFile file) {
        String result = "";
        try {
            String fileId = SequenceUtil.makeStringId();
            String name = file.getOriginalFilename();
            assert name != null;
            String suffixName = name.substring(name.lastIndexOf("."));
            String fileName = fileId + suffixName;
            String fileDir = LocalDate.now().toString();
            String parentPath = uploadProperty.getUploadPath() + fileDir;
            File filepath = new File(parentPath, fileName);
            if (!filepath.getParentFile().exists()) {
                filepath.getParentFile().mkdirs();
            }
            file.transferTo(filepath);

            SysFile fileDomain = new SysFile();
            fileDomain.setId(fileId);
            fileDomain.setFileDesc(name);
            fileDomain.setFileName(fileName);
            fileDomain.setTargetDate(LocalDate.now());
            fileDomain.setFilePath(filepath.getPath());
            fileDomain.setCreateTime(new Date());
            fileDomain.setFileSize(FileUtil.getPrintSize(filepath.length()));
            fileDomain.setFileType(suffixName.replace(".", ""));
            int flag = fileMapper.insert(fileDomain);
            if (flag > 0) {
                result = fileId;
            } else {
                result = "";
            }
        } catch (Exception e) {
            log.error("failed to upload file.detail message:{}", e.getMessage());
        }
        return result;
    }

    @Override
    public String uploadHeadImg(String userId, String base64Str) {
        String result = "";
        try {
            String fileId = SequenceUtil.makeStringId();
            String fileName = userId + ".jpg";
            String parentPath = uploadProperty.getUploadPath() + "userPhoto";

            File filepath = new File(parentPath, fileName);
            if (!filepath.getParentFile().exists()) {
                filepath.getParentFile().mkdirs();
            }
            ImageBase64Util.convertBase64ToFile(base64Str, parentPath, fileName);

            SysFile fileDomain = new SysFile();
            fileDomain.setId(fileId);
            fileDomain.setFileDesc(userId);
            fileDomain.setFileName(fileName);
            fileDomain.setTargetDate(LocalDate.now());
            fileDomain.setFilePath(filepath.getPath());
            fileDomain.setCreateTime(new Date());
            fileDomain.setFileSize(FileUtil.getPrintSize(filepath.length()));
            fileDomain.setFileType("jpg");
            int flag = fileMapper.insert(fileDomain);
            if (flag > 0) {
                result = fileId;
                User user = new User();
                user.setEnable(1);

                user.setId(Long.parseLong(userId));
                user.setHeadImgUrl( result);
                updateById(user);
            } else {
                result = "";
            }
        } catch (Exception e) {
            log.error("failed to upload file.detail message:{}", e.getMessage());
        }
        return result;
    }

}
